# 使用以下方法在运行的时候可以不打开浏览器，运行速度杠杠的
import datetime
import time
import os
import sys

from webdriver_manager.chrome import ChromeDriverManager

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
import requests
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
import Tools.myPrint
from Registration.Setting import *
from Tools import SendEmail
import tqdm




def get_Qiandao(user_name, user_password, idea):
    try:
        # 不开网页搜索
        option = webdriver.ChromeOptions()
        option.add_argument("headless")
        s = Service(ChromeDriverManager().install())
        driver = webdriver.Chrome(service=s, options=option)
        # 开网页搜索
        # driver = webdriver.Chrome(path)

        # 打开百度并搜素selenium
        driver.get("http://www.zuidaima.com/")
        # print(driver.title)
        driver.find_element(by=By.XPATH, value="/html/body/div[1]/div/div/div[2]/ul/li/a").click()
        time.sleep(1)
        driver.find_element(by=By.XPATH, value="/html/body/div[2]/div/form/div[2]/input").send_keys(user_name)
        driver.find_element(by=By.XPATH, value="/html/body/div[2]/div/form/div[3]/input").send_keys(user_password)
        driver.find_element(by=By.XPATH, value="/html/body/div[2]/div/form/div[5]/a[1]").click()
        time.sleep(1)
        driver.find_element(By.XPATH, "/html/body/div[1]/div/div/div[1]/ul/li[1]/a").click()
        time.sleep(4)
        driver.find_element(By.XPATH, "/html/body/div[3]/div[1]/div[1]/div[1]/form/textarea").click()
        driver.find_element(By.XPATH, "/html/body/div[3]/div[1]/div[1]/div[1]/form/textarea").send_keys(idea)
        driver.find_element(By.XPATH, "/html/body/div[3]/div[1]/div[1]/div[1]/form/div/span[2]/a").click()
        # print(driver.title)
        time.sleep(4)
        driver.close()
        return [True, str(user_name)+str(idea)+"sucess"]
    except Exception as e:
        print(e)
        return [False, str(e)+str(user_name)+str(idea)+"err"]


def jsb(username, password):
    # 不开网页搜索
    option = webdriver.ChromeOptions()
    option.add_argument("headless")
    s = Service(ChromeDriverManager().install())
    driver = webdriver.Chrome(service=s, options=option)
    try:
        driver.get("https://www.jisiba.com/login/")
        # 输入账号密码
        driver.find_element(by=By.XPATH,
                            value='//*[@id="app"]/div/div[2]/div/div/div[2]/form/div[1]/div/div/div/div/input').send_keys(
            username)
        driver.find_element(by=By.XPATH,
                            value='//*[@id="app"]/div/div[2]/div/div/div[2]/form/div[2]/div/div[1]/div/div/input').send_keys(
            password)

        # 点击提交
        driver.find_element(by=By.XPATH, value='//*[@id="app"]/div/div[2]/div/div/div[2]/form/button').click()
        time.sleep(3)

        # 判断是否已经签到
        s = driver.find_element(by=By.XPATH, value='//*[@id="app"]/div/div[2]/div/div/div/div[3]').get_attribute(
            'innerHTML')
        if '已签到' in s:
            return [True, "今天已经签到"]

        # 点击签到
        driver.find_element(by=By.XPATH,
                            value='//*[@id="app"]/div/div[2]/div/div/div/div[3]/div[1]/div[3]/div/div[2]/span').click()
        time.sleep(3)

        # --------------修改弹窗部分，找不到元素不点击--------------

        try:
            # 点击选择自己状态，
            driver.find_element(by=By.CLASS_NAME, value='radio-no-check').click()
            # 点击提交
            driver.find_element(by=By.XPATH, value='/html/body/div[2]/div/div[2]/div[2]/button').click()
        except Exception as e:
            print("无需选择自己状态")

        # --------------修改弹窗部分，找不到元素不点击--------------

        # 查看签到状态
        driver.get('https://www.jisiba.com/home')
        time.sleep(3)
        s = driver.find_element(by=By.XPATH, value='//*[@id="app"]/div/div[2]/div/div/div/div[3]').get_attribute(
            'innerHTML')
        # print(s)
        if '已签到' in s:
            return [True, ""]
        else:
            return [False, "签到失败"]
    except Exception as e:
        Tools.myPrint.myPrint_Err(e)
        return [False, "签到失败" + str(e)]
    finally:
        driver.close()
def get_lanzhou_weather():
    url = 'https://restapi.amap.com/v3/weather/weatherInfo?key=689bfca96107a49a90cef58c19122c6e&city=620100&extensions=all'
    req = requests.get(url)
    return req.json()['forecasts'][0]['city']+':'+req.json()['forecasts'][0]['casts'][0]['dayweather']+"   "+req.json()['forecasts'][0]['casts'][0]['nighttemp']+"-"+req.json()['forecasts'][0]['casts'][0]['daytemp']
def get_sentence():
    url = 'http://api.tianapi.com/zaoan/index?key=d8a416a3af4f3eb81e5786edf92682db'
    req = requests.get(url)
    return req.json()['newslist'][0]['content']
if __name__ == '__main__':
    while True:
        sum = len(user_passwords) + len(user_passwords_jsb)
        sentence=get_sentence()
        message.append(sentence)
        count = 0
        err_info = ""
        start_time = datetime.datetime.now()
        for user_password in user_passwords:
            m = message.pop(0)
            statue = get_Qiandao(user_password[0], user_password[1], m)
            message.append(m)
            time.sleep(2)
            err_info+=str(statue[1])+"<br>"
            if statue[0]:
                Tools.myPrint.myPrint_Success(user_password)
                count += 1
            else:
                # err_info.join(str(user_password[0]))
                # err_info.join(statue[1])
                Tools.myPrint.myPrint_Err(user_password)
        for user_password in user_passwords_jsb:
            statue = jsb(*user_password)
            if statue[0]:
                count += 1
            else:
                err_info += user_password[0] + statue[1]
        SendEmail.mail("自动签到", "成功" + str(count) + "失败" + str(sum - count)+"<br>"
                       +get_lanzhou_weather()+"<br>"
                       +sentence+ err_info+"<br>"
                       +"系统成功运行:",(datetime.datetime.now()-start_time).days,"天"
                       )
        
        
        
        
        all_time = Interval_time_secend
        all_time /= 10

        for i in tqdm.trange(int(all_time)):
            time.sleep(10)
